package demo;

import hcsdk.HCNetSDK;
import hcsdk.HCNetSDK.NET_DVR_FDLIB_PARAM;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jdesktop.application.Action;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author yangxiaofeng6
 */
public class FDLibBox extends javax.swing.JDialog {

    public static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE;

    public AlarmJavaDemoView m_alarm;
    /**
     * 人脸库ID
     */
    public int m_FDID;
    /**
     * 是否支持人脸功能
     */
    public boolean m_isSupportFDLib;
    public List<HCNetSDK.NET_DVR_FDLIB_PARAM> m_FDLibList;
    public NativeLong m_lUploadHandle;
    public NativeLong m_UploadStatus;
    public String m_picID;

    private javax.swing.JComboBox FDLibComboBox;
    private javax.swing.JButton FDLibDeletePicButton;
    private javax.swing.JButton FDLibGetButton;
    private javax.swing.JTextField FDLibNameTextField;
    private javax.swing.JButton FDLibUploadFileButton;
    private javax.swing.JButton createFDLibButton;
    private javax.swing.JButton deleteFDLibButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton searchFDLibButton;
    private javax.swing.JButton setThresholdValueButton;
    private javax.swing.JTextField thresholdValueTextField;

    /**
     * Creates new form FDLibBox
     */
    public FDLibBox(java.awt.Frame parent, AlarmJavaDemoView obj) {
        super(parent);
        initComponents();
        m_alarm = obj;
        m_FDLibList = new ArrayList<NET_DVR_FDLIB_PARAM>();
        m_lUploadHandle = new NativeLong(-1);
        m_UploadStatus = new NativeLong(-1);

        try {
            //查询是否支持人脸库
            if (GetFaceCapabilities()) {
                m_isSupportFDLib = true;
                searchFDLibButtonClick();
            } else {
                m_isSupportFDLib = false;
            }
        } catch (DocumentException ex) {
            Logger.getLogger(FDLibBox.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    //人脸能力集获取
    public boolean GetFaceCapabilities() throws DocumentException {
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT inBuf = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        inBuf.dwSize = inBuf.size();
        String url = "GET /ISAPI/Intelligent/FDLib/capabilities\r\n";

        HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(url.length());
        System.arraycopy(url.getBytes(), 0, ptrUrl.byValue, 0, url.length());
        ptrUrl.write();
        inBuf.lpRequestUrl = ptrUrl.getPointer();
        inBuf.dwRequestUrlLen = url.length();

        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT outBuf = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        outBuf.dwSize = outBuf.size();
        HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
        outBuf.lpOutBuffer = ptrOutByte.getPointer();
        outBuf.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;
        outBuf.write();

        if (hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, inBuf, outBuf)) {
            return true;
        } else {

            int code = hCNetSDK.NET_DVR_GetLastError();
            JOptionPane.showMessageDialog(null, "获取人脸能力集失败: " + code);
            return false;
        }
    }

    public boolean SearchFDLib() {
        try {
            if (m_isSupportFDLib) {
                //返回true，说明支持人脸
                HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
                struInput.dwSize = struInput.size();

                String str = "GET /ISAPI/Intelligent/FDLib\r\n";
                HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
                System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
                ptrUrl.write();
                struInput.lpRequestUrl = ptrUrl.getPointer();
                struInput.dwRequestUrlLen = str.length();

                HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
                struOutput.dwSize = struOutput.size();

                HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
                struOutput.lpOutBuffer = ptrOutByte.getPointer();
                struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;

                HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
                struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
                struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
                struOutput.write();

                if (hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
                    String xmlStr = struOutput.lpOutBuffer.getString(0);

                    //dom4j解析xml
                    Document document = DocumentHelper.parseText(xmlStr);
                    //获取根节点元素对象
                    Element FDLibBaseCfgList = document.getRootElement();

                    //同时迭代当前节点下面的所有子节点
                    Iterator<Element> iterator = FDLibBaseCfgList.elementIterator();
                    while (iterator.hasNext()) {
                        HCNetSDK.NET_DVR_FDLIB_PARAM tmp = new HCNetSDK.NET_DVR_FDLIB_PARAM();
                        Element e = iterator.next();
                        Iterator<Element> iterator2 = e.elementIterator();
                        while (iterator2.hasNext()) {
                            Element e2 = iterator2.next();
                            if ("id".equals(e2.getName())) {
                                String id = e2.getText();
                                tmp.dwID = Integer.parseInt(id);
                            }
                            if ("name".equals(e2.getName())) {
                                tmp.szFDName = e2.getText();
                            }
                            if ("FDID".equals(e2.getName())) {
                                String fdid = e2.getText();
                                tmp.dwFDID = Integer.parseInt(fdid);
                            }
                        }
                        m_FDLibList.add(tmp);
                    }

                } else {
                    int code = hCNetSDK.NET_DVR_GetLastError();
                    JOptionPane.showMessageDialog(null, "创建人脸库失败: " + code);
                    return false;
                }
            } else {
                return false;
            }
        } catch (DocumentException ex) {
            Logger.getLogger(FDLibBox.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        return true;
    }

    //创建人脸库
    public boolean CreateFDLib(String FDLibName) {
        try {
            if (m_isSupportFDLib) {
                //返回true，说明支持人脸
                HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
                struInput.dwSize = struInput.size();

                String str = "POST /ISAPI/Intelligent/FDLib\r\n";
                HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
                System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
                ptrUrl.write();
                struInput.lpRequestUrl = ptrUrl.getPointer();
                struInput.dwRequestUrlLen = str.length();

                String strInBuffer = new String("<CreateFDLibList><CreateFDLib><id>1</id><name>" + FDLibName + "</name><thresholdValue>1</thresholdValue><customInfo /></CreateFDLib></CreateFDLibList>");
                HCNetSDK.BYTE_ARRAY ptrByte = new HCNetSDK.BYTE_ARRAY(10 * HCNetSDK.BYTE_ARRAY_LEN);
                ptrByte.byValue = strInBuffer.getBytes();
                ptrByte.write();
                struInput.lpInBuffer = ptrByte.getPointer();
                struInput.dwInBufferSize = strInBuffer.length();
                struInput.write();

                HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
                struOutput.dwSize = struOutput.size();

                HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
                struOutput.lpOutBuffer = ptrOutByte.getPointer();
                struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;

                HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
                struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
                struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
                struOutput.write();

                if (hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
                    String xmlStr = struOutput.lpOutBuffer.getString(0);

                    //dom4j解析xml
                    Document document = DocumentHelper.parseText(xmlStr);
                    //获取根节点元素对象
                    Element FDLibInfoList = document.getRootElement();

                    //同时迭代当前节点下面的所有子节点
                    Iterator<Element> iterator = FDLibInfoList.elementIterator();
                    Element FDLibInfo = iterator.next();
                    Iterator<Element> iterator2 = FDLibInfo.elementIterator();
                    while (iterator2.hasNext()) {
                        Element e = iterator2.next();
                        if ("FDID".equals(e.getName())) {
                            String id = e.getText();
                            m_FDID = Integer.parseInt(id);
                        }
                        System.out.println(e.getName() + "：" + e.getText());
                    }
                } else {
                    int code = hCNetSDK.NET_DVR_GetLastError();
                    JOptionPane.showMessageDialog(null, "创建人脸库失败: " + code);
                    return false;
                }
            } else {
                return false;
            }
        } catch (DocumentException ex) {
            Logger.getLogger(FDLibBox.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        return true;
    }

    public boolean DeleteFDLib() {
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        struInput.dwSize = struInput.size();

        int index = FDLibComboBox.getSelectedIndex();
        int id = m_FDLibList.get(index).dwFDID;
        String str = "DELETE /ISAPI/Intelligent/FDLib/" + id;
        HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
        System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
        ptrUrl.write();
        struInput.lpRequestUrl = ptrUrl.getPointer();
        struInput.dwRequestUrlLen = str.length();

        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        struOutput.dwSize = struOutput.size();
        struOutput.write();

        if (hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
            JOptionPane.showMessageDialog(null, "删除人脸库成功");
            return true;
        } else {
            int code = hCNetSDK.NET_DVR_GetLastError();
            JOptionPane.showMessageDialog(null, "删除人脸库失败: " + code);
            return false;
        }
    }

    public boolean UploadFile(int index) {
        if (m_isSupportFDLib) {
            //返回true，说明支持人脸
            HCNetSDK.NET_DVR_FACELIB_COND struInput = new HCNetSDK.NET_DVR_FACELIB_COND();
            struInput.dwSize = struInput.size();
            struInput.szFDID = String.valueOf(m_FDLibList.get(index).dwFDID).getBytes();
            struInput.byConcurrent = 0;
            struInput.byCover = 1;
            struInput.byCustomFaceLibID = 0;

            struInput.write();
            Pointer lpInput = struInput.getPointer();

            NativeLong ret = hCNetSDK.NET_DVR_UploadFile_V40(m_alarm.lUserID, HCNetSDK.IMPORT_DATA_TO_FACELIB, lpInput, struInput.size(), null, null, 0);
            if (ret.longValue() == -1) {
                int code = hCNetSDK.NET_DVR_GetLastError();
                JOptionPane.showMessageDialog(null, "上传图片文件失败: " + code);
                return false;
            } else {
                m_lUploadHandle = ret;
                return true;
            }
        } else {
            return false;
        }
    }

    public void UploadSend() {
        FileInputStream picfile = null;
        FileInputStream xmlfile = null;
        int picdataLength = 0;
        int xmldataLength = 0;

        try {
            picfile = new FileInputStream(new File(System.getProperty("user.dir") + "\\face.jpg"));
            xmlfile = new FileInputStream(new File(System.getProperty("user.dir") + "\\data.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            picdataLength = picfile.available();
            xmldataLength = xmlfile.available();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if (picdataLength < 0 || xmldataLength < 0) {
            System.out.println("input file/xml dataSize < 0");
            return;
        }

        HCNetSDK.BYTE_ARRAY ptrpicByte = new HCNetSDK.BYTE_ARRAY(picdataLength);
        HCNetSDK.BYTE_ARRAY ptrxmlByte = new HCNetSDK.BYTE_ARRAY(xmldataLength);

        try {
            picfile.read(ptrpicByte.byValue);
            xmlfile.read(ptrxmlByte.byValue);
        } catch (IOException e2) {
            e2.printStackTrace();
        }

        ptrpicByte.write();
        ptrxmlByte.write();

        HCNetSDK.NET_DVR_SEND_PARAM_IN struSendParam = new HCNetSDK.NET_DVR_SEND_PARAM_IN();

        struSendParam.pSendData = ptrpicByte.getPointer();
        struSendParam.dwSendDataLen = picdataLength;
        struSendParam.pSendAppendData = ptrxmlByte.getPointer();
        struSendParam.dwSendAppendDataLen = xmldataLength;
        if (struSendParam.pSendData == null || struSendParam.pSendAppendData == null || struSendParam.dwSendDataLen == 0 || struSendParam.dwSendAppendDataLen == 0) {
            System.out.println("input file/xml data err");
            return;
        }

        struSendParam.byPicType = 1;
        struSendParam.dwPicMangeNo = 0;
        struSendParam.write();

        NativeLong iRet = hCNetSDK.NET_DVR_UploadSend(m_lUploadHandle, struSendParam.getPointer(), null);

        System.out.println("iRet=" + iRet);
        if (iRet.longValue() < 0) {
            System.out.println("NET_DVR_UploadSend fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        } else {
            System.out.println("NET_DVR_UploadSend success");
            System.out.println("dwSendDataLen =" + struSendParam.dwSendDataLen);
            System.out.println("dwSendAppendDataLen =" + struSendParam.dwSendAppendDataLen);
        }

        try {
            picfile.close();
            xmlfile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void UploadFaceLinData() {
        if (m_lUploadHandle.longValue() != -1) {
            if (hCNetSDK.NET_DVR_UploadClose(m_lUploadHandle)) {
                System.out.println("NET_DVR_UploadClose success");
            } else {
                System.out.println("NET_DVR_UploadClose fail,error=" + hCNetSDK.NET_DVR_GetLastError());
            }
        }

        int index = FDLibComboBox.getSelectedIndex();
        UploadFile(index);

        if (m_lUploadHandle.longValue() < 0) {
            System.out.println("NET_DVR_UploadFile_V40 fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        } else {
            System.out.println("NET_DVR_UploadFile_V40 success");
        }

        Thread thread = new Thread() {
            @Override
            public void run() {
                UploadSend();
                while (true) {
                    if (-1 == m_lUploadHandle.longValue()) {
                        return;
                    }

                    m_UploadStatus = getUploadState();
                    if (m_UploadStatus.longValue() == 1) {
                        HCNetSDK.NET_DVR_UPLOAD_FILE_RET struPicRet = new HCNetSDK.NET_DVR_UPLOAD_FILE_RET();
                        struPicRet.write();
                        Pointer lpPic = struPicRet.getPointer();

                        boolean bRet = hCNetSDK.NET_DVR_GetUploadResult(m_lUploadHandle, lpPic, struPicRet.size());
                        if (!bRet) {
                            System.out.println("NET_DVR_GetUploadResult failed with:" + hCNetSDK.NET_DVR_GetLastError());
                        } else {
                            System.out.println("NET_DVR_GetUploadResult succ");
                            struPicRet.read();
                            m_picID = new String(struPicRet.sUrl);
                            System.out.println("PicID:" + m_picID);
                            JOptionPane.showMessageDialog(null, "图片上传成功 PID:" + m_picID);
                        }

                        if (hCNetSDK.NET_DVR_UploadClose(m_lUploadHandle)) {
                            m_lUploadHandle.setValue(-1);
                        }

                    } else if (m_UploadStatus.longValue() >= 3 || m_UploadStatus.longValue() == -1) {
                        System.out.println("m_UploadStatus = " + m_UploadStatus);
                        hCNetSDK.NET_DVR_UploadClose(m_lUploadHandle);
                        m_lUploadHandle.setValue(-1);
                        break;
                    }
                }
            }
        };
        thread.start();
    }

    public NativeLong getUploadState() {
        IntByReference pInt = new IntByReference(0);
        m_UploadStatus = hCNetSDK.NET_DVR_GetUploadState(m_lUploadHandle, pInt);
        if (m_UploadStatus.longValue() == -1) {
            System.out.println("NET_DVR_GetUploadState fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        } else if (m_UploadStatus.longValue() == 2) {
            System.out.println("is uploading!!!!  progress = " + pInt.getValue());
        } else if (m_UploadStatus.longValue() == 1) {
            System.out.println("progress = " + pInt.getValue());
            System.out.println("Uploading Succ!!!!!");
        } else {
            System.out.println("NET_DVR_GetUploadState fail  m_UploadStatus=" + m_UploadStatus);
            System.out.println("NET_DVR_GetUploadState fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        }
        return m_UploadStatus;
    }

    public void SetFaceAppendData() {
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        struInput.dwSize = struInput.size();

        int index = FDLibComboBox.getSelectedIndex();
        int id = m_FDLibList.get(index).dwFDID;

        String str = "PUT /ISAPI/Intelligent/FDLib/" + id + "/picture/" + m_picID;
        HCNetSDK.BYTE_ARRAY ptrSetFaceAppendDataUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
        System.arraycopy(str.getBytes(), 0, ptrSetFaceAppendDataUrl.byValue, 0, str.length());
        ptrSetFaceAppendDataUrl.write();
        struInput.lpRequestUrl = ptrSetFaceAppendDataUrl.getPointer();
        struInput.dwRequestUrlLen = str.length();

        String strInBuffer = "<FaceAppendData><name>Name</name><bornTime>2000-01-01</bornTime><sex>male</sex><province /><certificateType /><certificateNumber /></FaceAppendData>";

        HCNetSDK.BYTE_ARRAY ptrByte = new HCNetSDK.BYTE_ARRAY(10 * 1024);
        ptrByte.byValue = strInBuffer.getBytes();
        ptrByte.write();
        struInput.lpInBuffer = ptrByte.getPointer();
        struInput.dwInBufferSize = strInBuffer.length();
        struInput.write();

        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        struOutput.dwSize = struOutput.size();

        HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
        struOutput.lpOutBuffer = ptrOutByte.getPointer();
        struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;

        HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
        struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
        struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
        struOutput.write();

        if (!hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
            System.out.println("PUT /ISAPI/Intelligent/FDLib/1/picture/1 failed with:" + m_alarm.lUserID + " " + hCNetSDK.NET_DVR_GetLastError());
            return;
        } else {
            System.out.println("PUT /ISAPI/Intelligent/FDLib/1/picture/1 success");
            System.out.println("dwReturnXMLSize=" + struOutput.dwReturnedXMLSize);
        }
    }

    public void DeleteFaceAppendData() {
        int index = FDLibComboBox.getSelectedIndex();
        int id = m_FDLibList.get(index).dwFDID;

        String str = "DELETE /ISAPI/Intelligent/FDLib/" + id + "/picture/" + m_picID;

        HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        struInput.dwSize = struInput.size();

        HCNetSDK.BYTE_ARRAY ptrDeleteFaceLibUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
        System.arraycopy(str.getBytes(), 0, ptrDeleteFaceLibUrl.byValue, 0, str.length());
        ptrDeleteFaceLibUrl.write();
        struInput.lpRequestUrl = ptrDeleteFaceLibUrl.getPointer();
        struInput.dwRequestUrlLen = str.length();
        struInput.lpInBuffer = null;
        struInput.dwInBufferSize = 0;
        struInput.write();

        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        struOutput.dwSize = struOutput.size();
        struOutput.lpOutBuffer = null;
        struOutput.dwOutBufferSize = 0;

        HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
        struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
        struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
        struOutput.write();

        if (!hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
            System.out.println("lpRequestUrl:" + str);
            System.out.println("NET_DVR_STDXMLConfig DELETE failed with:" + " " + hCNetSDK.NET_DVR_GetLastError());
        } else {
            System.out.println("lpRequestUrl:" + str);
            System.out.println("NET_DVR_STDXMLConfig DELETE Succ!!!!!!!!!!!!!!!");
            JOptionPane.showMessageDialog(null, "图片删除成功 PID:" + m_picID);
        }
    }

    public void GetFaceAppendData(int iUserID) {
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        struInput.dwSize = struInput.size();

        String str = "GET /ISAPI/Intelligent/FDLib/1/picture/1";
        HCNetSDK.BYTE_ARRAY ptrGetFaceAppendDataUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
        System.arraycopy(str.getBytes(), 0, ptrGetFaceAppendDataUrl.byValue, 0, str.length());
        ptrGetFaceAppendDataUrl.write();
        struInput.lpRequestUrl = ptrGetFaceAppendDataUrl.getPointer();
        struInput.dwRequestUrlLen = str.length();

        struInput.lpInBuffer = null;
        struInput.dwInBufferSize = 0;
        struInput.write();

        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        struOutput.dwSize = struOutput.size();

        HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
        struOutput.lpOutBuffer = ptrOutByte.getPointer();
        struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;

        HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
        struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
        struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
        struOutput.write();

        if (!hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
            System.out.println("GET /ISAPI/Intelligent/FDLib/1/picture failed with:" + m_alarm.lUserID + " " + hCNetSDK.NET_DVR_GetLastError());
            return;
        } else {
            System.out.println("GET /ISAPI/Intelligent/FDLib/1/picture success");
            System.out.println("dwReturnXMLSize=" + struOutput.dwReturnedXMLSize);
            JOptionPane.showMessageDialog(null, "删除人脸库图片成功 PID：" + m_picID);
        }
    }

    public boolean SetThresholdValue() {
        if (m_isSupportFDLib) {
            //返回true，说明支持人脸
            HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
            struInput.dwSize = struInput.size();

            String str = "PUT /ISAPI/Intelligent/channels/1/faceContrast\r\n";
            HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
            System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
            ptrUrl.write();
            struInput.lpRequestUrl = ptrUrl.getPointer();
            struInput.dwRequestUrlLen = str.length();

            int value = Integer.parseInt(thresholdValueTextField.getText());
            int index = FDLibComboBox.getSelectedIndex();
            String strInBuffer = new String("<FaceContrastList><FaceContrast><id>1</id><enable>true</enable><faceContrastType>faceContrast</faceContrastType><thresholdValue>" + value + "</thresholdValue><FDLibList><FDLib><id>" + m_FDLibList.get(index).dwID + "</id><FDID>" + m_FDLibList.get(index).dwFDID + "</FDID></FDLib></FDLibList></FaceContrast></FaceContrastList>");
            HCNetSDK.BYTE_ARRAY ptrByte = new HCNetSDK.BYTE_ARRAY(10 * HCNetSDK.BYTE_ARRAY_LEN);
            ptrByte.byValue = strInBuffer.getBytes();
            ptrByte.write();
            struInput.lpInBuffer = ptrByte.getPointer();
            struInput.dwInBufferSize = strInBuffer.length();
            struInput.write();

            HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
            struOutput.dwSize = struOutput.size();

            HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
            struOutput.lpOutBuffer = ptrOutByte.getPointer();
            struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;

            HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
            struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
            struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
            struOutput.write();

            if (hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
                JOptionPane.showMessageDialog(null, "设置阀值成功: " + value);
            } else {
                int code = hCNetSDK.NET_DVR_GetLastError();
                JOptionPane.showMessageDialog(null, "设置阀值失败: " + code);
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        FDLibComboBox = new javax.swing.JComboBox();
        searchFDLibButton = new javax.swing.JButton();
        deleteFDLibButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        FDLibNameTextField = new javax.swing.JTextField();
        createFDLibButton = new javax.swing.JButton();
        FDLibUploadFileButton = new javax.swing.JButton();
        FDLibDeletePicButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        thresholdValueTextField = new javax.swing.JTextField();
        setThresholdValueButton = new javax.swing.JButton();
        FDLibGetButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        FDLibComboBox.setName("FDLibComboBox"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(AlarmJavaDemoApp.class).getContext().getActionMap(FDLibBox.class, this);
        searchFDLibButton.setAction(actionMap.get("searchFDLibButtonClick")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(AlarmJavaDemoApp.class).getContext().getResourceMap(FDLibBox.class);
        searchFDLibButton.setText(resourceMap.getString("searchFDLibButton.text")); // NOI18N
        searchFDLibButton.setName("searchFDLibButton"); // NOI18N

        deleteFDLibButton.setAction(actionMap.get("deleteFDLibButtonClick")); // NOI18N
        deleteFDLibButton.setText(resourceMap.getString("deleteFDLibButton.text")); // NOI18N
        deleteFDLibButton.setName("deleteFDLibButton"); // NOI18N

        jLabel1.setName("jLabel1"); // NOI18N

        FDLibNameTextField.setName("FDLibNameTextField"); // NOI18N

        createFDLibButton.setAction(actionMap.get("createFDLibButtonClick")); // NOI18N
        createFDLibButton.setText(resourceMap.getString("createFDLibButton.text")); // NOI18N
        createFDLibButton.setName("createFDLibButton"); // NOI18N

        FDLibUploadFileButton.setAction(actionMap.get("FDLibUploadFileButtonClick")); // NOI18N
        FDLibUploadFileButton.setText(resourceMap.getString("FDLibUploadFileButton.text")); // NOI18N
        FDLibUploadFileButton.setName("FDLibUploadFileButton"); // NOI18N

        FDLibDeletePicButton.setAction(actionMap.get("FDLibDeletePicButtonClick")); // NOI18N
        FDLibDeletePicButton.setText(resourceMap.getString("FDLibDeletePicButton.text")); // NOI18N
        FDLibDeletePicButton.setName("FDLibDeletePicButton"); // NOI18N

        jLabel2.setName("jLabel2"); // NOI18N

        thresholdValueTextField.setName("thresholdValueTextField"); // NOI18N

        setThresholdValueButton.setAction(actionMap.get("setThresholdValueButtonClick")); // NOI18N
        setThresholdValueButton.setText(resourceMap.getString("setThresholdValueButton.text")); // NOI18N
        setThresholdValueButton.setName("setThresholdValueButton"); // NOI18N

        FDLibGetButton.setAction(actionMap.get("FDLibGetButtonClick")); // NOI18N
        FDLibGetButton.setText(resourceMap.getString("FDLibGetButton.text")); // NOI18N
        FDLibGetButton.setName("FDLibGetButton"); // NOI18N

        jLabel5.setName("jLabel5"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(99, 99, 99).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(FDLibGetButton).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel3).addComponent(FDLibComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(FDLibUploadFileButton).addComponent(jLabel4)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel1).addComponent(FDLibNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(36, 36, 36).addComponent(createFDLibButton)).addGroup(layout.createSequentialGroup().addGap(70, 70, 70).addComponent(jLabel5)).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(layout.createSequentialGroup().addComponent(jLabel2).addGap(50, 50, 50)).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(thresholdValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(FDLibDeletePicButton)).addGap(24, 24, 24))).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(setThresholdValueButton)).addGroup(layout.createSequentialGroup().addComponent(searchFDLibButton).addGap(48, 48, 48).addComponent(deleteFDLibButton))))).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(18, 18, 18).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLabel1).addComponent(createFDLibButton).addComponent(jLabel3).addComponent(FDLibNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(54, 54, 54).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(FDLibComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(searchFDLibButton).addComponent(deleteFDLibButton)).addGap(31, 31, 31).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(FDLibUploadFileButton).addComponent(FDLibDeletePicButton)).addGap(12, 12, 12).addComponent(jLabel2).addGap(18, 18, 18).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(thresholdValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel4).addComponent(setThresholdValueButton)).addGap(10, 10, 10).addComponent(jLabel5).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE).addComponent(FDLibGetButton).addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void searchFDLibButtonClick() {
        m_FDLibList.clear();
        FDLibComboBox.removeAllItems();
        if (SearchFDLib()) {
            for (int i = 0; i < m_FDLibList.size(); i++) {
                FDLibComboBox.addItem(m_FDLibList.get(i).szFDName);
            }
            FDLibComboBox.setSelectedIndex(0);
        }
    }

    @Action
    public void deleteFDLibButtonClick() {
        DeleteFDLib();
    }

    @Action
    public void createFDLibButtonClick() {
        String name = FDLibNameTextField.getText();
        if ("".equals(name)) {
            JOptionPane.showMessageDialog(null, "请输入人脸库名称");
        } else {
            if (CreateFDLib(name)) {
                searchFDLibButtonClick();
                JOptionPane.showMessageDialog(null, "人脸库创建成功");
            }
        }

    }

    @Action
    public void FDLibUploadFileButtonClick() {
        UploadFaceLinData();
    }

    @Action
    public void FDLibDeletePicButtonClick() {
        DeleteFaceAppendData();
    }

    @Action
    public void setThresholdValueButtonClick() {
        SetThresholdValue();
    }

    @Action
    public void FDLibGetButtonClick() {
        try {
            if (m_isSupportFDLib) {
                boolean isQuit = false;
                int pos = 1;
                while (!isQuit) {
                    //返回true，说明支持人脸

                    int index = FDLibComboBox.getSelectedIndex();
                    int id = m_FDLibList.get(index).dwFDID;

                    HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
                    struInput.dwSize = struInput.size();

                    String str = "POST /ISAPI/Intelligent/FDLib/FCSearch\r\n";
                    HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
                    System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
                    ptrUrl.write();
                    struInput.lpRequestUrl = ptrUrl.getPointer();
                    struInput.dwRequestUrlLen = str.length();

                /*<FCSearchDescription version="2.0" xmlns="http://www.std-cgi.org/ver20/XMLSchema">
                    <searchID>C7AFBBC1-B3B0-0001-939C-1F00C53C17A9</searchID>
                    <searchResultPosition>1</searchResultPosition>
                    <maxResults>40</maxResults>   每次返回搜索结果的条数
                    <snapStartTime>2016-09-18T23:59:59Z</snapStartTime>  开始时间
                    <snapEndTime>2017-09-18T23:59:59Z</snapEndTime>      结束时间
                    <similarity>
                        <min>0</min>   相似度最小值
                        <max>80</max>  相似度最大值
                    </similarity>
                    <FDIDList>
                        <FDID>1</FDID> 人脸库ID
                    </FDIDList>
                </FCSearchDescription>*/
                    String strInBuffer = new String("<FCSearchDescription><searchID>C7AFBBC1-B3B0-0001-939C-1F00C53C17A9</searchID><searchResultPosition>" + pos + "</searchResultPosition><maxResults>100</maxResults><snapStartTime>2016-09-18T23:59:59Z</snapStartTime><snapEndTime>2017-09-18T23:59:59Z</snapEndTime><similarity><min>0</min><max>80</max></similarity><FDIDList><FDID>" + id + "</FDID></FDIDList></FCSearchDescription>");
                    HCNetSDK.BYTE_ARRAY ptrByte = new HCNetSDK.BYTE_ARRAY(10 * HCNetSDK.BYTE_ARRAY_LEN);
                    ptrByte.byValue = strInBuffer.getBytes();
                    ptrByte.write();
                    struInput.lpInBuffer = ptrByte.getPointer();
                    struInput.dwInBufferSize = strInBuffer.length();
                    struInput.write();

                    HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
                    struOutput.dwSize = struOutput.size();

                    HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
                    struOutput.lpOutBuffer = ptrOutByte.getPointer();
                    struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;

                    HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
                    struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
                    struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
                    struOutput.write();

                    if (hCNetSDK.NET_DVR_STDXMLConfig(m_alarm.lUserID, struInput, struOutput)) {
                        String xmlStr = struOutput.lpOutBuffer.getString(0);

                        //dom4j解析xml
                        Document document = DocumentHelper.parseText(xmlStr);
                        //获取根节点元素对象
                        Element FCSearchResult = document.getRootElement();

                        //同时迭代当前节点下面的所有子节点
                        Iterator<Element> iterator = FCSearchResult.elementIterator();
                        while (iterator.hasNext()) {
                            Element e = iterator.next();
                            if ("responseStatusStrg".equals(e.getName())) {
                                if ("MORE".equals(e.getText())) {
                                    isQuit = false;
                                } else {
                                    isQuit = true;
                                }
                            }
                            if ("numOfMatches".equals(e.getName())) {
                                pos += Integer.parseInt(e.getText());
                                System.out.println("pos：" + pos);
                            }
                            if ("totalMatches".equals(e.getName())) {
                                if (isQuit) {
                                    System.out.println("搜索到的总数是：" + e.getText());
                                }
                            }
                            if ("MatchList".equals(e.getName())) {
                                Iterator<Element> iterator2 = e.elementIterator();  //MatchElementList
                                while (iterator2.hasNext()) {
                                    Element e2 = iterator2.next();  //MatchElement
                                    Iterator<Element> iterator3 = e2.elementIterator();
                                    while (iterator3.hasNext()) {
                                        Element e3 = iterator3.next();
                                        if ("snapPicURL".equals(e3.getName())) {
                                            System.out.println("snapPicURL：" + e3.getText());
                                        }
                                        if ("facePicURL".equals(e3.getName())) {
                                            System.out.println("facePicURL：" + e3.getText());
                                        }
                                    }

                                }

                            }

                        }
                    } else {
                        int code = hCNetSDK.NET_DVR_GetLastError();
                        JOptionPane.showMessageDialog(null, "获取失败: " + code);
                        return;
                    }
                }
            } else {
                return;
            }
        } catch (DocumentException ex) {
            Logger.getLogger(FDLibBox.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
        return;
    }
    // End of variables declaration//GEN-END:variables

}
